package com.openspring.platform.dao.impl;

import java.util.List;
import org.springframework.stereotype.Repository;
import com.openspring.framework.dao.AbstractSpringGenericDAO;
import com.openspring.framework.extend.spring.EntityPropertyRowMapper;
import com.openspring.framework.util.MD5Utils;
import com.openspring.platform.dao.UserDAO;
import com.openspring.platform.model.Role;
import com.openspring.platform.model.User;

@Repository("userDAO")
public class UserDAOImpl extends AbstractSpringGenericDAO<User, Long> implements UserDAO {

	@Override
	public User getUser(String loginName, String password) {
		String sql = "SELECT * FROM emp.t_platform_user WHERE \"loginName\" = ? AND password = ?";
		List<User> users = getJdbcTemplate().query(sql, new EntityPropertyRowMapper<User>(User.class), loginName, MD5Utils.encrypt(password));
		return users.isEmpty() ? null : users.get(0);
	}

	@Override
	public List<Role> getRoles(Long id) {
		String sql = "SELECT * FROM emp.t_platform_role WHERE id IN (SELECT \"roleId\" FROM emp.t_platform_user_role WHERE \"userId\" = ?)";
		return getJdbcTemplate().query(sql, new EntityPropertyRowMapper<Role>(Role.class) , id);
	}

	@Override
	public int updatePassword(Long id, String password) {
		String sql = "UPDATE emp.t_platform_user SET password = ? WHERE id = ?";
		return getJdbcTemplate().update(sql, MD5Utils.encrypt(password), id);
	}
}
